package com.an.dao;

import com.an.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int getMatchCount(String userName, String password) {
        String sql = "select count(*) from t_user where user_name = ? and password = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, new String[]{userName, password});
    }

    public User findUserByUserName(String username) {
        String sql = "select * from t_user where user_name = ?";
        final User user = new User();
        jdbcTemplate.query(sql, new Object[]{username}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                user.setCredits(resultSet.getInt("credits"));
                user.setLastIp(resultSet.getString("last_ip"));
                user.setLastVisit(resultSet.getDate("last_visit"));
                user.setUserName(resultSet.getString("user_name"));
                user.setUserId(resultSet.getInt("user_id"));
            }
        });
        return user;
    }

    public void updateLoginInfo(User user) {
        String sql = "update t_user set last_visit = ? ,last_ip = ?,credits = ? where user_id = ?";
        jdbcTemplate.update(sql, new Object[]{user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()});

    }


}
